package OThinker.H3.Controller.Controllers.ProcessModel;

import OThinker.Common.Data.BoolMatchValue;
import OThinker.Common.Data.ComparisonOperatorType;
import OThinker.Common.DateTimeUtil;
import OThinker.Common.DotNetToJavaStringHelper;
import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.enums.State;
import OThinker.Common.Organization.enums.UnitType;
import OThinker.Common.RefObject;
import OThinker.Common.SplitUtil;
import OThinker.Common.TimeSpan;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Controller.ViewModels.ActionResult;
import OThinker.H3.Controller.ViewModels.FilterDataViewModel;
import OThinker.H3.Controller.ViewModels.Item;
import OThinker.H3.Controller.ViewModels.TestServiceViewModel;
import OThinker.H3.Entity.Acl.BizObjectAcl;
import OThinker.H3.Entity.Acl.FunctionNode;
import OThinker.H3.Entity.BizBus.BizService.BizServiceInvokingContext;
import OThinker.H3.Entity.BizBus.BizService.BizStructure;
import OThinker.H3.Entity.BizBus.BizService.BizStructureUtility;
import OThinker.H3.Entity.BizBus.BizService.ItemSchema;
import OThinker.H3.Entity.BizBus.BizService.MethodSchema;
import OThinker.H3.Entity.BizBus.Filter.And;
import OThinker.H3.Entity.BizBus.Filter.Filter;
import OThinker.H3.Entity.BizBus.Filter.ItemMatcher;
import OThinker.H3.Entity.BizBus.Filter.SortBy;
import OThinker.H3.Entity.BizBus.Filter.SortDirection;
import OThinker.H3.Entity.Configs.ResourceManager;
import OThinker.H3.Entity.Data.DataLogicType;
import OThinker.H3.Entity.Data.Metadata.EnumerableMetadata;
import OThinker.H3.Entity.DataModel.ActionType;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.DataModel.BizObjectSchema;
import OThinker.H3.Entity.DataModel.BizQuery;
import OThinker.H3.Entity.DataModel.BizQueryAction;
import OThinker.H3.Entity.DataModel.BizQueryColumn;
import OThinker.H3.Entity.DataModel.BizQueryItem;
import OThinker.H3.Entity.DataModel.ControlType;
import OThinker.H3.Entity.DataModel.FilterType;
import OThinker.H3.Entity.DataModel.PropertySchema;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Instance.InstanceContext;
import OThinker.H3.Entity.Tracking.UserLogType;
import OThinker.H3.Entity.WorkSheet.BizSheet;
import OThinker.H3.Entity.WorkSheet.SheetType;
import OThinker.H3.Entity.WorkflowTemplate.WorkflowDocument.PublishedWorkflowTemplate;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.base.enums.SheetMode;
import com.h3bpm.base.model.GridViewModel;
import com.h3bpm.base.model.PagerInfo;
import com.h3bpm.base.user.UserValidator;
import com.h3bpm.base.util.InstanceOperationLogHelper;
import com.h3bpm.base.util.SheetUtility;
import com.h3bpm.web.common.H3Property;
import com.h3bpm.web.ext.controller.UserPortalController;
import data.DataRow;
import data.DataTable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping({"/Portal/RunBizQuery"})
@Scope("prototype")
@Controller
/* loaded from: RunBizQueryController.class */
public class RunBizQueryController extends ControllerBase {
    @Autowired
    private UserPortalController userPortalController;
    private static final long serialVersionUID = 7543727883349836888L;
    private static final Logger LOGGER = LoggerFactory.getLogger(RunBizQueryController.class);
    private String privateSchemaCode;
    private String privateQueryCode;
    private BizQuery _Query;
    private List<BizQueryItem> _lstVisibleQueryItems;
    private String _OutputPropertyMappings;
    private String _InputPropertyMappings;
    private String _ListMethod = "GetList";
    private BizObjectSchema _Schema = null;
    protected List<Map<String, String>> GirdColumns = new ArrayList();

    public String getFunctionCode() {
        return "ProcessModel_BizMasterData";
    }

    public String getSchemaCode() {
        return this.privateSchemaCode;
    }

    public void setSchemaCode(String value) {
        this.privateSchemaCode = value;
    }

    public String getQueryCode() {
        return this.privateQueryCode;
    }

    public void setQueryCode(String value) {
        this.privateQueryCode = value;
    }

    public final String getCtrlID() {
        return this.request.getParameter("CtrlID");
    }

    protected final String getOpenType() throws UnsupportedEncodingException {
        if (this.request.getParameter("OpenType") == null) {
            return "0";
        }
        String openType = URLDecoder.decode(this.request.getParameter("OpenType"), H3Property.UTF_8);
        return DotNetToJavaStringHelper.isNullOrEmpty(openType) ? "0" : openType;
    }

    protected final boolean getIsPopup() {
        return !DotNetToJavaStringHelper.isNullOrEmpty(this.request.getParameter("IsPopup"));
    }

    public String getListMethod() throws Exception {
        if (getQuery() != null) {
            return this._ListMethod;
        }
        return this._ListMethod;
    }

    public void setListMethod(String value) {
        this._ListMethod = value;
    }

    protected final BizQuery getQuery() throws Exception {
        if (this._Query == null) {
            this._Query = getEngine().getBizObjectManager().GetBizQuery(getQueryCode());
            if (this._Query == null) {
                throw new Exception(String.format("主数据[%1$s]不存在查询编码[%2$s]。", getSchemaCode(), getQueryCode()));
            }
        }
        return this._Query;
    }

    private List<BizQueryItem> getlstVisibleQueryItems() throws Exception {
        if (this._lstVisibleQueryItems == null || this._lstVisibleQueryItems.size() == 0) {
            this._lstVisibleQueryItems = new ArrayList();
            if (!(getQuery() == null || getQuery().getQueryItems() == null)) {
                for (BizQueryItem item : getQuery().getQueryItems()) {
                    if (item.getVisible() == BoolMatchValue.True) {
                        item.setPropertyCode(item.getPropertyName());
                        PropertySchema propertySchema = getSchema().GetProperty(item.getPropertyCode());
                        if (propertySchema != null) {
                            item.setPropertyName(propertySchema.getDisplayName());
                        }
                        this._lstVisibleQueryItems.add(item);
                    }
                }
            }
        }
        return this._lstVisibleQueryItems;
    }

    protected final BizObjectSchema getSchema() throws Exception {
        if (this._Schema == null) {
            this._Schema = getEngine().getBizObjectManager().GetPublishedSchema(getSchemaCode());
        }
        return this._Schema;
    }

    protected boolean getActionVisible() {
        return true;
    }

    public final String getOutputPropertyMappings() throws UnsupportedEncodingException {
        if (DotNetToJavaStringHelper.isNullOrEmpty(this._OutputPropertyMappings)) {
            if (this.request.getParameter("OutputParams") == null) {
                return "";
            }
            this._OutputPropertyMappings = URLDecoder.decode(this.request.getParameter("OutputParams"), H3Property.UTF_8);
        }
        return this._OutputPropertyMappings;
    }

    public final void setOutputPropertyMappings(String value) {
        this._OutputPropertyMappings = value;
    }

    private String getInputPropertyMappings() throws UnsupportedEncodingException {
        if (this._InputPropertyMappings == null) {
            this._InputPropertyMappings = this.request.getParameter("InputParam") == null ? "" : URLDecoder.decode(this.request.getParameter("InputParam"), H3Property.UTF_8);
        }
        return this._InputPropertyMappings;
    }

    @RequestMapping(value = {"/GetRunBizQueryData"}, method = {RequestMethod.GET})
    @ResponseBody
    public final ActionResult GetRunBizQueryData(String schemaCode, String queryCode) throws UnsupportedEncodingException, Exception {
        setSchemaCode(URLDecoder.decode(schemaCode, "utf-8"));
        setQueryCode(URLDecoder.decode(queryCode, "utf-8"));
        ActionResult result = new ActionResult();
        Map<String, Object> param = new HashMap<>();
        CreateColumns();
        param.put("isFrame", Boolean.valueOf(getOpenType().equals("1")));
        param.put("isReturn", Boolean.valueOf(SplitUtil.Splits(getOutputPropertyMappings(), new String[]{" | "}, true).length > 0));
        param.put("outputPropertyMappings", getOutputPropertyMappings());
        param.put("CtrlID", getCtrlID());
        param.put("SchemaCode", getSchemaCode());
        param.put("ActionVisible", Boolean.valueOf(getActionVisible()));
        param.put("Param_BizObjectID", "BizObjectID");
        param.put("Param_SchemaCode", "SchemaCode");
        param.put("GirdColumns", this.GirdColumns);
        param.put("BizQueryActions", GetActions());
        param.put("DisplayFormats", GetDisplayFormats());
        param.put("FilterData", GetVisibleFilterData());
        param.put("ListDefault", Integer.valueOf(this._Query.getListDefault().getValue()));
        result.setSuccess(true);
        result.setExtend(param);
        return result;
    }

    @RequestMapping(value = {"/GetGridData"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public final Map<String, Object> GetGridData(String schemaCode, String queryCode, String FilterStr, PagerInfo pageInfo) throws Exception {
        LOGGER.info("schemaCode:" + schemaCode + ",queryCode:" + queryCode + ",FilterStr:" + FilterStr);
        setSchemaCode(URLDecoder.decode(schemaCode, "utf-8"));
        setQueryCode(URLDecoder.decode(queryCode, "utf-8"));
        int totalCount = 0;
        RefObject<Integer> tempRef_totalCount = new RefObject<>(0);
        List<Object> objList = new ArrayList<>();
        if (schemaCode.equals("UserAll")) {
            int pageSize = pageInfo.getPageSize();
            int currentPageIndex = pageInfo.getPageIndex();
            JSONObject jsonObject = JSONObject.parseObject(FilterStr);
            LOGGER.info("进入正文");
            UserValidator userValidator = getUserValidator();
            LOGGER.info("code:{}", userValidator.getUserCode());
            Object[] rowOjb = this.userPortalController.GetGridData(userValidator.getUserCode(), (String) jsonObject.get("emp_number"), (String) jsonObject.get("emp_name"), (String) jsonObject.get("dept_name"), (String) jsonObject.get("emp_personneltype"), (String) jsonObject.get("emp_incumbencystate"), (String) jsonObject.get("emp_mobilephone")).toArray();
            if (rowOjb != null) {
                totalCount = rowOjb.length;
            }
            int startIndex = 0;
            int endIndex = totalCount;
            if (pageSize > 0 && currentPageIndex > 0) {
                startIndex = (currentPageIndex - 1) * pageSize < 0 ? 0 : (currentPageIndex - 1) * pageSize;
                endIndex = currentPageIndex * pageSize >= totalCount ? totalCount : currentPageIndex * pageSize;
            }
            for (int i = startIndex; i < endIndex; i++) {
                objList.add((rowOjb instanceof Object[] ? rowOjb : null)[i]);
            }
            tempRef_totalCount.argvalue = Integer.valueOf(totalCount);
        } else if (schemaCode.equals("selectUserExtAll")) {
            int pageSize2 = pageInfo.getPageSize();
            int currentPageIndex2 = pageInfo.getPageIndex();
            JSONObject jsonObject2 = JSONObject.parseObject(FilterStr);
            LOGGER.info("进入正文");
            UserValidator userValidator2 = getUserValidator();
            LOGGER.info("code:{}", userValidator2.getUserCode());
            Object[] rowOjb2 = this.userPortalController.GetGridDataExtend(userValidator2.getUserCode(), (String) jsonObject2.get("emp_number"), (String) jsonObject2.get("emp_name"), (String) jsonObject2.get("dept_name"), (String) jsonObject2.get("emp_personneltype"), (String) jsonObject2.get("emp_incumbencystate"), (String) jsonObject2.get("emp_mobilephone")).toArray();
            if (rowOjb2 != null) {
                totalCount = rowOjb2.length;
            }
            int startIndex2 = 0;
            int endIndex2 = totalCount;
            if (pageSize2 > 0 && currentPageIndex2 > 0) {
                startIndex2 = (currentPageIndex2 - 1) * pageSize2 < 0 ? 0 : (currentPageIndex2 - 1) * pageSize2;
                endIndex2 = currentPageIndex2 * pageSize2 >= totalCount ? totalCount : currentPageIndex2 * pageSize2;
            }
            for (int i2 = startIndex2; i2 < endIndex2; i2++) {
                objList.add((rowOjb2 instanceof Object[] ? rowOjb2 : null)[i2]);
            }
            tempRef_totalCount.argvalue = Integer.valueOf(totalCount);
        } else {
            objList = GetGridDataList(FilterStr, pageInfo, tempRef_totalCount);
        }
        this.request.getSession().setAttribute(this.request.getRequestURI(), (Object) null);
        Map<String, Object> extend = new HashMap<>();
        extend.put("Rows", objList);
        extend.put("Total", tempRef_totalCount.argvalue);
        return extend;
    }

    private List<Object> GetGridDataList(String filterStr, PagerInfo pageInfo, RefObject<Integer> totalCount) throws Exception {
        Date dateValue;
        Filter filter = (DotNetToJavaStringHelper.isNullOrEmpty(filterStr) || "{}".equals(filterStr)) ? new Filter() : GetFilter(filterStr);
        if (getQuery().getQueryItems() != null && DotNetToJavaStringHelper.isNullOrEmpty(filterStr)) {
            filter = GetFilter("");
        }
        totalCount.argvalue = 0;
        int pageSize = pageInfo.getPageSize();
        int currentPageIndex = pageInfo.getPageIndex();
        String SortName = this.request.getParameter("sortname");
        String SortOrder = this.request.getParameter("sortorder");
        SortDirection sortDirection = SortDirection.Ascending;
        if (DotNetToJavaStringHelper.isNullOrEmpty(SortName)) {
            int i = 0;
            while (true) {
                if (i >= getQuery().getColumns().size()) {
                    break;
                } else if (((BizQueryColumn) getQuery().getColumns().get(i)).getVisible() == BoolMatchValue.True.getValue()) {
                    filter.AddSortBy(new SortBy(((BizQueryColumn) getQuery().getColumns().get(i)).getPropertyName(), SortDirection.Ascending));
                    break;
                } else {
                    i++;
                }
            }
        } else if (!DotNetToJavaStringHelper.isNullOrEmpty(SortOrder) && SortOrder.toLowerCase().equals("desc")) {
            sortDirection = SortDirection.Descending;
        }
        filter.AddSortBy(new SortBy(SortName, sortDirection));
        if (filter.getSortByCollection() == null || filter.getSortByCollection().length == 0) {
            Iterator it = getQuery().getColumns().iterator();
            while (true) {
                if (!it.hasNext()) {
                    break;
                }
                BizQueryColumn column = (BizQueryColumn) it.next();
                if (column.getVisible() == BoolMatchValue.True.getValue()) {
                    filter.AddSortBy(new SortBy(column.getPropertyName(), SortDirection.Ascending));
                    break;
                }
            }
        }
        if (pageSize > 0) {
            filter.setFromRowNum((currentPageIndex - 1) * pageSize < 1 ? 1 : ((currentPageIndex - 1) * pageSize) + 1);
            filter.setToRowNum((filter.getFromRowNum() + pageSize) - 1);
        }
        filter.setRequireCount(true);
        BizObject[] objs = getSchema().GetList(getEngine().getOrganization(), getEngine().getMetadataRepository(), getEngine().getBizObjectManager(), getUserValidator().getUserID(), getListMethod(), filter, totalCount);
        List<Object> dataList = new ArrayList<>();
        LOGGER.info("GetGridData.dataList总数:"+(objs!=null?objs.length:0));
        LOGGER.info("GetGridData.totalCount总数:"+(totalCount!=null?totalCount.getValue():0));
        if (objs != null) {
            if (pageInfo.getPageIndex() <= 0) {
                pageInfo.setPageIndex(1);
            }
            int index = 0;
            System.out.printf("HANDLE PAGE DATA - PAGE %d STARTINDEX %d ENDINDEX %d%n", Integer.valueOf(pageInfo.getPageIndex()), Integer.valueOf(pageInfo.getStartIndex()), Integer.valueOf(pageInfo.getEndIndex()));
            List<String> VisiblePropertyNames = new ArrayList<>();
            if (getSchema().getProperties() != null) {
                for (PropertySchema p : getSchema().getProperties()) {
                    VisiblePropertyNames.add(p.getName());
                }
            }
            List<String> UnitIDList = new ArrayList<>();
            for (BizObject obj : objs) {
                if (objs.length > pageInfo.getPageSize()) {
                    index++;
                    if (index >= pageInfo.getStartIndex()) {
                        if (index > pageInfo.getEndIndex()) {
                            break;
                        }
                    } else {
                        continue;
                    }
                }
                if (obj.getValueTable() != null) {
                    Map<String, Object> dicValueTable = new HashMap<>();
                    for (String pName : VisiblePropertyNames) {
                        if (obj.getValueTable().containsKey(pName)) {
                            if (getSchema().GetProperty(pName).getLogicType() == DataLogicType.SingleParticipant || pName.equals(H3Property.CREATEDBY) || pName.equals("CreatedByParentId")) {
                                UnitIDList.add(obj.getValueTable().get(pName) + "");
                            } else if (getSchema().GetProperty(pName).getLogicType() == DataLogicType.MultiParticipant) {
                                HashMap<String, Object> map = obj.getValueTable();
                                if (map.get(pName) != null && (map.get(pName) instanceof String[]) && !ArrayUtils.isEmpty((String[]) map.get(pName))) {
                                    for (String participant : (String[]) map.get(pName)) {
                                        UnitIDList.add(participant);
                                    }
                                }
                            }
                        }
                    }
                    List<Unit> Units = getEngine().getOrganization().GetUnits(UnitIDList);
                    Map<String, Unit> UnitDictionary = new HashMap<>();
                    if (Units != null && Units.size() > 0) {
                        for (Unit u : Units) {
                            if (!UnitDictionary.containsKey(u.getObjectID())) {
                                UnitDictionary.put(u.getObjectID(), u);
                            }
                        }
                    }
                    for (String pName2 : VisiblePropertyNames) {
                        if (!(!obj.getValueTable().containsKey(pName2) || getSchema().GetProperty(pName2).getLogicType() == DataLogicType.Comment || getSchema().GetProperty(pName2).getLogicType() == DataLogicType.Attachment)) {
                            if (getSchema().GetProperty(pName2).getLogicType() == DataLogicType.SingleParticipant) {
                                if (UnitDictionary.containsKey(obj.getValueTable().get(pName2) + "")) {
                                    dicValueTable.put(pName2, GetUnitDisplayHtml(UnitDictionary.get(obj.getValueTable().get(pName2) + "")));
                                } else {
                                    dicValueTable.put(pName2, obj.getValueTable().get(pName2) == null ? "" : obj.getValueTable().get(pName2) + "");
                                }
                            } else if (getSchema().GetProperty(pName2).getLogicType() == DataLogicType.MultiParticipant) {
                                HashMap<String, Object> map2 = obj.getValueTable();
                                if (map2.get(pName2) != null) {
                                    if (!(map2.get(pName2) instanceof String[]) || ArrayUtils.isEmpty((String[]) map2.get(pName2))) {
                                        dicValueTable.put(pName2, obj.getValueTable().get(pName2));
                                    } else {
                                        String multiParticipantString = "";
                                        String[] strArr = (String[]) map2.get(pName2);
                                        for (String participant2 : strArr) {
                                            if (UnitDictionary.containsKey(participant2)) {
                                                multiParticipantString = multiParticipantString + GetUnitDisplayHtml(UnitDictionary.get(participant2)) + ";";
                                            } else {
                                                multiParticipantString = multiParticipantString + participant2 + ";";
                                            }
                                        }
                                        dicValueTable.put(pName2, multiParticipantString);
                                    }
                                }
                            } else if (getSchema().GetProperty(pName2).getLogicType() == DataLogicType.DateTime) {
                                Object value = obj.getValueTable().get(pName2);
                                if (null == value) {
                                    dicValueTable.put(pName2, "");
                                } else if (!(value instanceof String) || !StringUtils.isBlank(value.toString())) {
                                    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    if (value instanceof Date) {
                                        dateValue = (Date) value;
                                    } else {
                                        dateValue = fmt.parse(value.toString());
                                    }
                                    Calendar cal = Calendar.getInstance();
                                    cal.setTime(dateValue);
                                    if (cal.get(1) < 1971 || cal.get(1) > 9000) {
                                        dicValueTable.put(pName2, "-");
                                    } else {
                                        dicValueTable.put(pName2, fmt.format(dateValue));
                                    }
                                } else {
                                    dicValueTable.put(pName2, "");
                                }
                            } else {
                                dicValueTable.put(pName2, obj.getValueTable().get(pName2));
                            }
                        }
                    }
                    dataList.add(dicValueTable);
                }
            }
        }
        return dataList;
    }

    @RequestMapping(value = {"/InvokeMethod"}, method = {RequestMethod.POST})
    @ResponseBody
    public final ActionResult InvokeMethod(String bizSchemaCode, String bizObjectID, String methodName, String rowData) throws Exception {
        ActionResult result = new ActionResult();
        String BizSchemaCode = bizSchemaCode.trim();
        String BizObjectID = bizObjectID.trim();
        String MethodName = methodName.trim();
        if (StringUtils.isBlank(MethodName) || "null".equalsIgnoreCase(MethodName)) {
            String[] errors = {ResourceManager.getString("RunBizQuery_BizMethodEmpty")};
            result.setSuccess(false);
            result.setErrors(errors);
            return result;
        }
        UserValidator userValidator = getUserValidator();
        BizObject bizObject = new BizObject(getEngine().getOrganization(), getEngine().getMetadataRepository(), getEngine().getBizObjectManager(), getEngine().getBizBus(), getEngine().getBizObjectManager().GetPublishedSchema(BizSchemaCode), userValidator.getUserID(), userValidator.getUser().getParentID());
        bizObject.setObjectID(BizObjectID);
        bizObject.Load((InstanceData) null);
        if (StringUtils.isEmpty(methodName) || "null".equalsIgnoreCase(methodName)) {
            result.setResult(false);
            result.setErrors(new String[]{"未绑定业务服务方法！"});
            return result;
        }
        if (StringUtils.isNotBlank(rowData)) {
            JSONObject parseObject = JSONObject.parseObject(rowData);
            for (String key : parseObject.keySet()) {
                parseObject.getString(key);
                bizObject.SetValue(key, parseObject.getString(key));
            }
        }
        if (MethodName.equals("Remove")) {
            if (!getUserValidator().ValidateBizObjectAdmin(BizSchemaCode, "", bizObject.getOwnerId() == null ? "" : bizObject.getOwnerId())) {
                result.setResult(false);
                result.setErrors(new String[]{"无管理权限"});
                return result;
            }
            bizObject.invoke(MethodName);
            result.setResult(true);
            result.setNeedRefresh(true);
            addLog(bizObject.getSchema(), userValidator.getUserID());
            return result;
        }
        bizObject.invoke(MethodName);
        result.setResult(true);
        return result;
    }

    private void addLog(BizObjectSchema schema, String userId) {
        String logName = "";
        String schemaCode = schema.getSchemaCode();
        try {
            PublishedWorkflowTemplate workflow = getEngine().getWorkflowManager().GetDefaultWorkflow(schemaCode);
            if (workflow == null) {
                FunctionNode functionNode = getEngine().getFunctionAclManager().GetFunctionNodeByCode(schemaCode);
                if (functionNode != null) {
                    logName = functionNode.getDisplayName();
                }
            } else {
                logName = getEngine().getWorkflowManager().GetClauseDisplayName(schemaCode) + "." + workflow.getWorkflowVersion();
            }
        } catch (Exception e) {
            LOGGER.error("get workflow info error,{}", e);
        }
        InstanceOperationLogHelper.addLog(userId, schemaCode, logName, UserLogType.BizQueryDataDelete, false);
    }

    @RequestMapping(value = {"/EditBizObject"}, method = {RequestMethod.GET})
    @ResponseBody
    public final void EditBizObject(String BizObjectID, String SchemaCode, String SheetCode, String Mode, String AfterSave, String IsEditInstanceData, String isMobile, String go, HttpServletResponse servletResponse) throws IOException, Exception {
        String BizObjectID2 = StringEscapeUtils.escapeSql(BizObjectID);
        String SchemaCode2 = StringEscapeUtils.escapeSql(SchemaCode);
        String SheetCode2 = StringEscapeUtils.escapeSql(SheetCode);
        String Mode2 = StringEscapeUtils.escapeSql(Mode);
        StringEscapeUtils.escapeSql(AfterSave);
        String IsEditInstanceData2 = StringEscapeUtils.escapeSql(IsEditInstanceData);
        StringEscapeUtils.escapeSql(isMobile);
        String go2 = StringEscapeUtils.escapeSql(go);
        if (0 == 0) {
            String url = "";
            String IsMobile = "false";
            if ("true".equals(this.request.getParameter("IsMobile")) || "true".equals(this.request.getParameter("isMobile"))) {
                IsMobile = "true";
            }
            boolean mobile = Boolean.valueOf(IsMobile).booleanValue();
            SheetMode sheetmode = SheetMode.valueOf(Mode2);
            if (!DotNetToJavaStringHelper.isNullOrEmpty(IsEditInstanceData2)) {
                url = GetWorkSheetUrl(SchemaCode2, BizObjectID2, sheetmode, mobile) + "&EditInstanceData=true";
            } else {
                BizSheet sheet = getEngine().getBizSheetManager().GetBizSheetByCode(SheetCode2);
                if (sheet == null) {
                    List<BizSheet> sheets = getEngine().getBizSheetManager().GetBizSheetBySchemaCode(SchemaCode2);
                    if (sheets == null || sheets.size() == 0) {
                        throw new RuntimeException("流程包{" + SchemaCode2 + "}表单不存在，请检查。");
                    }
                    sheet = sheets.get(0);
                }
                if (sheet.getSheetType() == SheetType.DefaultSheet || sheet.getSheetType() == SheetType.FormEngineSheet) {
                    url = GetWorkSheetUrl(SchemaCode2, BizObjectID2, sheet, sheetmode, mobile);
                } else if (sheet.getSheetType() == SheetType.CustomSheet) {
                    url = "/Portal/" + GetWorkSheetUrl(SchemaCode2, BizObjectID2, sheet, sheetmode, mobile) + "EditInstanceData=true";
                }
            }
            if (!DotNetToJavaStringHelper.isNullOrEmpty(this.request.getParameter("onlyData"))) {
                url = url + "&onlyData=true";
            }
            if (!DotNetToJavaStringHelper.isNullOrEmpty(go2)) {
                url = url + "&go=" + go2;
            }
            servletResponse.sendRedirect(url);
        }
    }

    @RequestMapping(value = {"/EditBizObjectSheet"}, method = {RequestMethod.POST})
    @ResponseBody
    public final ActionResult EditBizObjectSheet(String BizObjectID, String SchemaCode, String SheetCode, String Mode, boolean IsMobile, String EditInstanceData) throws Exception {
        String url;
        ActionResult result = new ActionResult(false, "");
        SheetMode sheetMode = SheetMode.Work;
        SheetMode sheetMode2 = SheetMode.valueOf(Mode);
        if (!DotNetToJavaStringHelper.isNullOrEmpty(EditInstanceData)) {
            url = GetWorkSheetUrl(SchemaCode, BizObjectID, sheetMode2, IsMobile) + "&EditInstanceData=true";
        } else {
            BizSheet sheet = getEngine().getBizSheetManager().GetBizSheetByCode(SheetCode);
            if (sheet == null) {
                List<BizSheet> sheets = getEngine().getBizSheetManager().GetBizSheetBySchemaCode(SchemaCode);
                if (sheets == null || sheets.size() == 0) {
                    throw new RuntimeException("流程包{" + SchemaCode + "}表单不存在，请检查。");
                }
                sheet = sheets.get(0);
            }
            url = GetWorkSheetUrl(SchemaCode, BizObjectID, sheet, sheetMode2, IsMobile);
        }
        result.setMessage(url);
        result.setSuccess(true);
        return result;
    }

    @RequestMapping(value = {"/EditBizObjectSheet"}, method = {RequestMethod.GET})
    @ResponseBody
    public final Object EditBizObjectSheet2(String BizObjectID, String SchemaCode, String SheetCode, String Mode, boolean IsMobile, String EditInstanceData) throws Exception {
        String url;
        Map<String, Object> temp = new HashMap<>();
        ActionResult result = new ActionResult(false, "");
        SheetMode sheetMode = SheetMode.Work;
        SheetMode sheetMode2 = SheetMode.valueOf(Mode);
        if (ValidateAuthorization(BizObjectID, SchemaCode, sheetMode2, SchemaCode) == BoolMatchValue.False) {
            result.setSuccess(false);
            result.setMessage("MvcController_Perission");
            temp.put("Message", result.getMessage());
            temp.put("Extend", result.getExtend());
            temp.put("ExceptionCode", result.getExceptionCode());
            temp.put("Success", Boolean.valueOf(result.getSuccess()));
            return result;
        }
        if (!DotNetToJavaStringHelper.isNullOrEmpty(EditInstanceData)) {
            url = GetWorkSheetUrl(SchemaCode, BizObjectID, sheetMode2, IsMobile) + "&EditInstanceData=true";
        } else {
            BizSheet sheet = getEngine().getBizSheetManager().GetBizSheetByCode(SheetCode);
            if (sheet == null) {
                List<BizSheet> sheets = getEngine().getBizSheetManager().GetBizSheetBySchemaCode(SchemaCode);
                if (sheets == null || sheets.size() == 0) {
                    throw new RuntimeException("流程包{" + SchemaCode + "}表单不存在，请检查。");
                }
                sheet = sheets.get(0);
            }
            url = GetWorkSheetUrl(SchemaCode, BizObjectID, sheet, sheetMode2, IsMobile) + "&onlyData=true";
        }
        result.setMessage(url);
        result.setSuccess(true);
        temp.put("Message", result.getMessage());
        temp.put("Extend", result.getExtend());
        temp.put("ExceptionCode", result.getExceptionCode());
        temp.put("Success", Boolean.valueOf(result.getSuccess()));
        return temp;
    }

    public BoolMatchValue ValidateAuthorization(String BizObjectID, String SchemaCode, SheetMode SheetMode, String WorkflowCode) throws Exception {
        InstanceData instanceData = null;
        List<InstanceContext> context = getEngine().getInstanceManager().GetInstanceContextsByBizObject(SchemaCode, BizObjectID);
        if (context != null && context.size() > 0) {
            instanceData = new InstanceData(getEngine(), context.get(0).getInstanceId(), getUserValidator().getUserID());
        }
        if (SheetMode == SheetMode.Originate) {
            return BoolMatchValue.True;
        }
        if (getUserValidator().ValidateOrgAdmin(instanceData.getBizObject().getOwnerId()) || getUserValidator().ValidateBizObjectAdmin(SchemaCode, (String) null, instanceData.getBizObject().getOwnerId())) {
            return BoolMatchValue.True;
        }
        return BoolMatchValue.False;
    }

    @RequestMapping(value = {"/GetVisibleFilterData"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public final List<FilterDataViewModel> GetVisibleFilterData() throws Exception {
        List<FilterDataViewModel> list = new ArrayList<>();
        if (getlstVisibleQueryItems() != null) {
            for (int i = 0; i < getlstVisibleQueryItems().size(); i++) {
                BizQueryItem s = getlstVisibleQueryItems().get(i);
                FilterDataViewModel tempVar = new FilterDataViewModel();
                tempVar.setDefaultValue(s.getDefaultValue());
                tempVar.setDisplayType(s.getFilterType() != FilterType.Scope.getValue() ? s.getDisplayType() : ControlType.TextBox.getValue());
                tempVar.setFilterType(s.getFilterType());
                tempVar.setLogicType(GetPropertyLogicTypeByName(s.getPropertyCode()));
                tempVar.setParentIndex(s.getParentIndex());
                tempVar.setPropertyCode(s.getPropertyCode());
                tempVar.setPropertyName(GetPropertyDisplayNameByName(s.getPropertyCode()));
                tempVar.setPropertyType(s.getPropertyType().getValue());
                tempVar.setSelectedValues(GetFilterSelectedValues(s.getSelectedValues(), String.valueOf(s.getDisplayType()), GetPropertyLogicTypeByName(s.getPropertyCode())));
                tempVar.setVisible(s.getVisible().getValue());
                list.add(tempVar);
            }
        }
        return list;
    }

    private List<Item> GetFilterSelectedValues(String selectedValue, String displayType, String logicType) throws Exception {
        List<Item> list = new ArrayList<>();
        List<EnumerableMetadata> enumDatas = null;
        if (!DotNetToJavaStringHelper.isNullOrEmpty(selectedValue)) {
            enumDatas = getEngine().getMetadataRepository().GetByCategory(selectedValue);
        }
        if (ControlType.DropdownList.getValue() == Integer.parseInt(displayType)) {
            list.add(new Item("全部", ""));
        }
        if (enumDatas != null && enumDatas.size() > 0) {
            for (int i = 0; i < enumDatas.size(); i++) {
                EnumerableMetadata s = enumDatas.get(i);
                Item temp = new Item();
                temp.setValue(s.getCode());
                temp.setText(s.getEnumValue());
                list.add(temp);
            }
        } else if (!DotNetToJavaStringHelper.isNullOrEmpty(selectedValue)) {
            TestServiceViewModel model = null;
            MethodSchema method = null;
            try {
                model = (TestServiceViewModel) new ObjectMapper().readValue(selectedValue, TestServiceViewModel.class);
                if (model != null) {
                    method = getEngine().getBizBus().GetMethod(model.getServiceCode(), model.getRunMethod());
                }
            } catch (Exception e) {
                LOGGER.error(">> " + e.toString());
            }
            if (model == null || method == null) {
                boolean isBool = false;
                if (logicType.equals(DataLogicType.Bool.toString())) {
                    isBool = true;
                }
                String[] selectedValueArr = DotNetToJavaStringHelper.trimEnd(selectedValue, new Character[]{';'}).split(";");
                for (String s2 : selectedValueArr) {
                    Item temp2 = new Item();
                    temp2.setValue(s2);
                    temp2.setText(isBool ? "1".equals(s2) ? "True" : "False" : s2);
                    list.add(temp2);
                }
            } else {
                BizStructure param = null;
                if (method.getParamSchema() != null) {
                    param = BizStructureUtility.Create(method.getParamSchema());
                }
                BizStructure ret = null;
                try {
                    ret = getEngine().getBizBus().Invoke(new BizServiceInvokingContext(getUserValidator().getUserID(), model.getServiceCode(), method.getServiceVersion(), method.getMethodName(), param));
                } catch (Exception e2) {
                    LOGGER.error(">> " + e2.toString());
                }
                if (!(ret == null || ret.getSchema() == null)) {
                    for (Object ItemSchema : ret.getSchema().getItems()) {
                        ItemSchema item = (ItemSchema) ItemSchema;
                        DataLogicType type = item.getLogicType();
                        Object obj = ret.getItem(item.getName());
                        if (type == DataLogicType.BizStructureArray) {
                            DataTable table = null;
                            BizStructure[] bizStructures = (BizStructure[]) obj;
                            if (bizStructures != null) {
                                int length = bizStructures.length;
                                int i2 = 0;
                                while (true) {
                                    if (i2 >= length) {
                                        break;
                                    }
                                    BizStructure st = bizStructures[i2];
                                    if (st != null) {
                                        table = BizStructureUtility.ToTable(st.getSchema(), bizStructures);
                                        break;
                                    }
                                    i2++;
                                }
                            }
                            if (table != null && table.getRows().size() > 0) {
                                for (int i3 = 0; i3 < table.getRows().size(); i3++) {
                                    DataRow row = table.getRows().get(i3);
                                    try {
                                        String Value = "";
                                        String Text = "";
                                        if (!DotNetToJavaStringHelper.isNullOrEmpty(model.getText()) && !DotNetToJavaStringHelper.isNullOrEmpty(model.getValue()) && row.getTable().getColumns().equals(model.getText()) && row.getTable().getColumns().equals(model.getValue())) {
                                            Value = row.getString(model.getValue()) + "";
                                            Text = row.getString(model.getText()) + "";
                                        } else if (row.getArrayList().length >= 2) {
                                            Value = row.getString(model.getValue());
                                            Text = row.getString(model.getText()) + "";
                                        } else if (row.getArrayList().length == 1) {
                                            Value = row.getString(0);
                                            Text = row.getString(0) + "";
                                        }
                                        Item temp3 = new Item();
                                        temp3.setValue(Value);
                                        temp3.setText(Text);
                                        list.add(temp3);
                                    } catch (Exception e1) {
                                        LOGGER.error(">> " + e1.toString());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    public final String GetPropertyDisplayNameByName(String propertyName) throws Exception {
        PropertySchema propertySchema = GetPropertySchemaByName(propertyName);
        if (null == propertySchema) {
            return "";
        }
        return propertySchema.getDisplayName().toString();
    }

    public final String GetPropertyLogicTypeByName(String propertyName) throws Exception {
        PropertySchema propertySchema = GetPropertySchemaByName(propertyName);
        if (null == propertySchema) {
            return "";
        }
        return propertySchema.getLogicType().toString();
    }

    private PropertySchema GetPropertySchemaByName(String propertyName) throws Exception {
        if (getSchema() != null) {
            return getSchema().GetProperty(propertyName);
        }
        return null;
    }

    private Map<String, String> GetDisplayFormats() throws Exception {
        if (getQuery() == null || getQuery().getColumns() == null) {
            return null;
        }
        Map<String, String> dicDisplayFormats = new HashMap<>();
        for (BizQueryColumn column : getQuery().getColumns()) {
            if (column.getVisible() == BoolMatchValue.True.getValue() && !DotNetToJavaStringHelper.isNullOrEmpty(column.getDisplayFormat()) && column.getDisplayFormat().indexOf("null") == -1) {
                dicDisplayFormats.put(column.getPropertyName(), column.getDisplayFormat());
            }
        }
        return dicDisplayFormats;
    }

    private String GetUnitDisplayHtml(Unit Unit) throws InstantiationException, IllegalAccessException {
        if (Unit == null) {
            return null;
        }
        String url = null;
        switch (AnonymousClass1.$SwitchMap$OThinker$Common$Organization$enums$UnitType[Unit.getUnitType().ordinal()]) {
            case 1:
                url = getPortalRoot().concat("/admin/TabMaster.html?url=/Portal/admin/Organization/EditGroup.htmlMode=View&ID=") + Unit.getObjectID();
                break;
            case 2:
                url = getPortalRoot().concat("/admin/TabMaster.html?url=/Portal/admin/Organization/EditOrgUnit.html?Mode=View&ID=") + Unit.getObjectID();
                break;
            case 3:
                url = getPortalRoot().concat("/admin/TabMaster.html?url=/Portal/admin/Organization/EditPost.html?Mode=View&ID=") + Unit.getObjectID();
                break;
            case 4:
                url = getPortalRoot().concat("/admin/TabMaster.html?url=/Portal/admin/Organization/EditUser.html?Mode=View&ID=") + Unit.getObjectID();
                break;
        }
        if (!DotNetToJavaStringHelper.isNullOrEmpty(url)) {
            return "" + Unit.getName();
        }
        return "" + Unit.getName();
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: OThinker.H3.Controller.Controllers.ProcessModel.RunBizQueryController$1  reason: invalid class name */
    /* loaded from: RunBizQueryController$1.class */
    public static /* synthetic */ class AnonymousClass1 {
        static final /* synthetic */ int[] $SwitchMap$OThinker$Common$Organization$enums$UnitType = new int[UnitType.values().length];

        static {
            try {
                $SwitchMap$OThinker$Common$Organization$enums$UnitType[UnitType.Group.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$OThinker$Common$Organization$enums$UnitType[UnitType.OrganizationUnit.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$OThinker$Common$Organization$enums$UnitType[UnitType.Post.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$OThinker$Common$Organization$enums$UnitType[UnitType.User.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$OThinker$Common$Organization$enums$UnitType[UnitType.Unspecified.ordinal()] = 5;
            } catch (NoSuchFieldError e5) {
            }
        }
    }

    protected final Filter GetFilter(String filterStr) throws Exception {
        Filter filter = new Filter();
        And and = new And();
        filter.setMatcher(and);
        List<String> columnList = new ArrayList<>();
        PropertySchema[] properties = getSchema().getProperties();
        for (PropertySchema property : properties) {
            if (property.getTypeSearchable() || property.getLogicType() == DataLogicType.MultiParticipant) {
                columnList.add(property.getName());
            }
        }
        String[] columns = new String[columnList.size()];
        for (int i = 0; i < columns.length; i++) {
            columns[i] = columnList.get(i);
        }
        filter.setReturnItems(columns);
        if (getQuery().getColumns() == null) {
            throw new RuntimeException(String.format("没有给主数据：%1$s的查询：%2$s添加可以显示的字段", getSchemaCode(), getQueryCode()));
        }
        List<String> filterItems = new ArrayList<>();
        if (!(getlstVisibleQueryItems() == null || getQuery().getQueryItems() == null)) {
            String[] paramValues = SplitUtil.Splits(getInputPropertyMappings().replace("|", "@"), new String[]{"@"}, true);
            for (BizQueryItem queryItem : getQuery().getQueryItems()) {
                if (queryItem.getFilterType() == FilterType.SystemParam.getValue() && getSchema().GetProperty(queryItem.getPropertyName()) != null) {
                    and.Add(new ItemMatcher(queryItem.getPropertyName(), ComparisonOperatorType.Equal, SheetUtility.GetSystemParamValue(getUserValidator(), queryItem.getDefaultValue())));
                } else if (queryItem.getVisible() == BoolMatchValue.False) {
                    for (String v : paramValues) {
                        if (v.indexOf(",") > -1) {
                            String key = v.substring(0, v.indexOf(","));
                            String value = v.substring(v.indexOf(",") + 1);
                            if (key.equals(queryItem.getPropertyName())) {
                                filterItems.add(queryItem.getPropertyName());
                                and.Add(new ItemMatcher(queryItem.getPropertyName(), ComparisonOperatorType.Equal, value));
                            }
                        }
                    }
                }
            }
        }
        ObjectMapper mapper = new ObjectMapper();
        JavaType javaType = mapper.getTypeFactory().constructParametricType(Map.class, new Class[]{String.class, Object.class});
        Map<String, Object> filterDic = new HashMap<>();
        if (!DotNetToJavaStringHelper.isNullOrEmpty(filterStr)) {
            filterDic = (Map) mapper.readValue(filterStr, javaType);
        }
        for (String key2 : filterDic.keySet()) {
            Object value2 = filterDic.get(key2);
            if (value2 instanceof String) {
                filterDic.put(key2, StringEscapeUtils.escapeSql(String.valueOf(value2)));
            }
        }
        for (FilterDataViewModel filterItem : GetVisibleFilterData()) {
            String paramValue = "";
            BizQueryItem query = GetQueryItemByName(getlstVisibleQueryItems(), filterItem.getPropertyCode());
            String paramName = filterItem.getPropertyCode();
            String start = null;
            String end = null;
            if (filterDic.containsKey(filterItem.getPropertyCode()) && filterDic.get(filterItem.getPropertyCode()) != null && filterDic.get(filterItem.getPropertyCode()).toString().length() > 0) {
                if (filterDic.get(filterItem.getPropertyCode()).toString().indexOf("start") > 0 && filterDic.get(filterItem.getPropertyCode()).toString().indexOf("end") > 0) {
                    Map<String, Object> result = (Map) filterDic.get(filterItem.getPropertyCode());
                    start = (String) result.get("start");
                    if (DotNetToJavaStringHelper.isNullOrEmpty(start)) {
                        result.put("start", DateTimeUtil.getDateToString(DateTimeUtil.minValue()));
                    }
                    end = (String) result.get("end");
                    if (DotNetToJavaStringHelper.isNullOrEmpty(end)) {
                        result.put("end", DateTimeUtil.getDateToString(DateTimeUtil.maxValue()));
                    }
                }
                paramValue = DotNetToJavaStringHelper.trimEnd(filterDic.get(filterItem.getPropertyCode()).toString(), new Character[]{';'});
            }
            if (filterItem.getFilterType() == 2) {
                ObjectMapper mapper2 = new ObjectMapper();
                Map<String, String> child = (Map) mapper2.readValue(net.sf.json.JSONObject.fromObject(paramValue).toString(), mapper2.getTypeFactory().constructParametricType(HashMap.class, new Class[]{String.class, String.class}));
                String fromValue = child.containsKey("start") ? child.get("start") : "";
                String toValue = child.containsKey("start") ? child.get("end") : "";
                if (child.size() != 0) {
                    if (DataLogicType.DateTime.toString().equals(filterItem.getLogicType())) {
                        Date t = new Date();
                        try {
                            t = DateTimeUtil.getStringToDate(fromValue);
                        } catch (Exception e) {
                        }
                        if (DateTimeUtil.getYear(t) == 1 || DateTimeUtil.getYear(t) == 1753 || DateTimeUtil.getYear(t) == 9999) {
                            fromValue = "";
                        }
                        boolean tempVar = true;
                        try {
                            t = DateTimeUtil.getStringToDate(toValue);
                        } catch (Exception e2) {
                            tempVar = false;
                        }
                        if (tempVar) {
                            toValue = DateTimeUtil.getDateToString(t);
                        }
                        if (DateTimeUtil.getYear(t) == 1 || DateTimeUtil.getYear(t) == 1753 || DateTimeUtil.getYear(t) == 9999) {
                            toValue = "";
                        }
                    }
                    if (!"".equals(fromValue) && !"".equals(start)) {
                        and.Add(new ItemMatcher(paramName, ComparisonOperatorType.NotBelow, fromValue));
                    }
                    if (!"".equals(toValue) && !"".equals(end)) {
                        and.Add(new ItemMatcher(paramName, ComparisonOperatorType.NotAbove, toValue));
                    }
                }
            } else if (query != null) {
                String[] params = paramValue.split(";");
                if (query == null || query.getFilterType() != FilterType.Contains.getValue()) {
                    if (!DotNetToJavaStringHelper.isNullOrEmpty(paramValue)) {
                        if (params.length > 1) {
                            for (int i2 = 0; i2 < params.length; i2++) {
                                and.Add(new ItemMatcher(paramName, ComparisonOperatorType.In, params));
                            }
                        } else {
                            and.Add(new ItemMatcher(paramName, ComparisonOperatorType.Equal, paramValue));
                        }
                    }
                } else if (params.length > 1) {
                    for (int i3 = 0; i3 < params.length; i3++) {
                        and.Add(new ItemMatcher(paramName, ComparisonOperatorType.In, params));
                    }
                } else {
                    and.Add(new ItemMatcher(paramName, ComparisonOperatorType.Contain, paramValue));
                }
            }
        }
        if (getQuery().getQueryItems() != null) {
            for (BizQueryItem item : getQuery().getQueryItems()) {
                if (item.getVisible() == BoolMatchValue.False && item.getFilterType() != FilterType.SystemParam.getValue() && !filterItems.contains(item.getPropertyName())) {
                    and.Add(new ItemMatcher(item.getPropertyName(), item.getFilterType() == FilterType.Contains.getValue() ? ComparisonOperatorType.Contain : ComparisonOperatorType.Equal, item.getDefaultValue()));
                }
            }
        }
        return filter;
    }

    private BizQueryItem GetQueryItemByName(List<BizQueryItem> queryItems, String name) {
        for (BizQueryItem queryItem : queryItems) {
            if (name.equals(queryItem.getPropertyCode())) {
                return queryItem;
            }
        }
        return null;
    }

    private List<BizQueryAction> GetActions() throws Exception {
        if (!getActionVisible()) {
            return null;
        }
        List<BizQueryAction> BizQueryActions = getQuery().getBizActions();
        if (BizQueryActions != null && BizQueryActions.size() > 0) {
            for (BizQueryAction action : BizQueryActions) {
                if (DotNetToJavaStringHelper.isNullOrEmpty(action.getIcon())) {
                    if (action.getActionCode().equals("AddNew")) {
                        action.setIcon("fa fa-plus");
                    }
                    if (action.getActionCode().equals("Edit")) {
                        action.setIcon("fa fa-edit");
                    }
                    if (action.getActionCode().equals("Delete")) {
                        action.setIcon("fa fa-minus");
                    }
                }
                if (action.getActionType() == ActionType.OpenUrl.getValue() && !DotNetToJavaStringHelper.isNullOrEmpty(action.getUrl()) && !action.getUrl().toLowerCase().startsWith("http:") && !action.getUrl().toLowerCase().startsWith("https:")) {
                    if (action.getUrl().toLowerCase().startsWith("www.")) {
                        action.setUrl("http://" + action.getUrl());
                    } else {
                        action.setUrl(GetUriPath(action.getUrl()));
                    }
                }
            }
        }
        return BizQueryActions;
    }

    public final String GetUriPath(String url) {
        if (getPortalRoot().equals("")) {
            return url;
        }
        if (DotNetToJavaStringHelper.isNullOrEmpty(url)) {
            return null;
        }
        return getPortalRoot().concat(url).replace("\\", "/");
    }

    private void CreateColumns() throws Exception {
        PropertySchema p;
        if (getQuery().getColumns() != null) {
            for (BizQueryColumn column : getQuery().getColumns()) {
                if (column.getVisible() == BoolMatchValue.True.getValue() && (p = getSchema().GetProperty(column.getPropertyName())) != null) {
                    Map<String, String> dicCloumns = new HashMap<>();
                    dicCloumns.put("display", p == null ? p.getName() : p.getDisplayName());
                    dicCloumns.put("name", p.getName());
                    if (column.getWidth() > 0) {
                        dicCloumns.put("width", column.getWidth() + "");
                    } else if (column.getWidth() < 0) {
                        dicCloumns.put("hide", "true");
                    }
                    this.GirdColumns.add(dicCloumns);
                }
            }
        }
    }

    @RequestMapping(value = {"/GetGridDataForPortal"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object GetGridDataForPortal(String schemaCode, String queryCode, String filterStr, PagerInfo pageInfo) throws Exception {
        String filterStr2 = StringEscapeUtils.escapeSql(filterStr);
        String schemaCode2 = StringEscapeUtils.escapeSql(schemaCode);
        String queryCode2 = StringEscapeUtils.escapeSql(queryCode);
        if (StringUtils.isEmpty(queryCode2) || Objects.equals(queryCode2, "null")) {
            return ActionResult.fail("RunBizQuery.QueryCodeEmpty");
        }
        setSchemaCode(URLDecoder.decode(schemaCode2, "utf-8"));
        setQueryCode(URLDecoder.decode(queryCode2, "utf-8"));
        if (DotNetToJavaStringHelper.isNullOrEmpty(filterStr2)) {
            filterStr2 = "{}";
        }
        RefObject<Integer> tempRef_totalCount = new RefObject<>(0);
        List<Object> objList = GetGridDataListForPortal(filterStr2, pageInfo, tempRef_totalCount);
        LOGGER.info("GetGridDataListForPortal.tempRef_totalCount总数:"+(tempRef_totalCount!=null?tempRef_totalCount.getValue():0));
        return new GridViewModel<>(((Integer) tempRef_totalCount.getValue()), objList, pageInfo.getsEcho());
    }

    private List<Object> GetGridDataListForPortal(String filterStr, PagerInfo pageInfo, RefObject<Integer> totalCount) throws Exception {
        String[] participants;
        Filter filter = GetFilter(filterStr);
        totalCount.argvalue = 0;
        int pageSize = pageInfo.getPageSize();
        int currentPageIndex = pageInfo.getPageIndex();
        String SortName = this.request.getParameter("sortname");
        String SortOrder = this.request.getParameter("sortorder");
        SortDirection sortDirection = SortDirection.Ascending;
        if (DotNetToJavaStringHelper.isNullOrEmpty(SortName)) {
            int i = 0;
            while (true) {
                if (i >= getQuery().getColumns().size()) {
                    break;
                } else if (((BizQueryColumn) getQuery().getColumns().get(i)).getVisible() == BoolMatchValue.True.getValue()) {
                    filter.AddSortBy(new SortBy(((BizQueryColumn) getQuery().getColumns().get(i)).getPropertyName(), SortDirection.Ascending));
                    break;
                } else {
                    i++;
                }
            }
        } else if (!DotNetToJavaStringHelper.isNullOrEmpty(SortOrder) && "desc".equals(SortOrder.toLowerCase())) {
            sortDirection = SortDirection.Descending;
        }
        filter.AddSortBy(new SortBy(SortName, sortDirection));
        if (filter.getSortByCollection() == null || filter.getSortByCollection().length == 0) {
            Iterator it = getQuery().getColumns().iterator();
            while (true) {
                if (!it.hasNext()) {
                    break;
                }
                BizQueryColumn column = (BizQueryColumn) it.next();
                if (column.getVisible() == BoolMatchValue.True.getValue()) {
                    filter.AddSortBy(new SortBy(column.getPropertyName(), SortDirection.Ascending));
                    break;
                }
            }
        }
        if (pageSize > 0) {
            filter.setFromRowNum((currentPageIndex - 1) * pageSize < 1 ? 1 : ((currentPageIndex - 1) * pageSize) + 1);
            filter.setToRowNum((filter.getFromRowNum() + pageSize) - 1);
        }
        filter.setRequireCount(true);
        BizObject[] objs = getSchema().GetList(getEngine().getOrganization(), getEngine().getMetadataRepository(), getEngine().getBizObjectManager(), getUserValidator().getUserID(), getListMethod(), filter, totalCount);
        List<Object> dataList = new ArrayList<>();
        LOGGER.info("GetGridDataListForPortal.dataList总数:"+ (objs!=null?objs.length:0));
        LOGGER.info("GetGridDataListForPortal.totalCount总数:"+(totalCount!=null?totalCount.getValue():0));
        totalCount.setValue(totalCount.getValue());
        if (objs != null) {
            for (BizObject biz : objs) {
                for (int j = 0; j < getQuery().getColumns().size(); j++) {
                    Object o = biz.getItem(((BizQueryColumn) getQuery().getColumns().get(j)).getPropertyName());
                    if (o == null || !(o instanceof BizObject[])) {
                        if (o != null && (o instanceof Object[])) {
                            Object[] obj = (Object[]) o;
                            if (obj == null || !(obj[0] instanceof String)) {
                                ItemSchema is = (ItemSchema) obj[0];
                                if (DataLogicType.Comment == is.getLogicType()) {
                                    biz.setItem(((BizQueryColumn) getQuery().getColumns().get(j)).getPropertyName(), "");
                                }
                                if (DataLogicType.Attachment == is.getLogicType()) {
                                    biz.setItem(((BizQueryColumn) getQuery().getColumns().get(j)).getPropertyName(), "");
                                }
                            }
                        }
                        if ((o instanceof ItemSchema) && ((ItemSchema) o).getLogicType() == DataLogicType.Attachment) {
                            biz.setItem(((BizQueryColumn) getQuery().getColumns().get(j)).getPropertyName(), "");
                        }
                    } else {
                        biz.setItem(((BizQueryColumn) getQuery().getColumns().get(j)).getPropertyName(), "");
                    }
                }
            }
            List<String> VisiblePropertyNames = new ArrayList<>();
            if (getSchema().getProperties() != null) {
                for (PropertySchema p : getSchema().getProperties()) {
                    VisiblePropertyNames.add(p.getName());
                }
            }
            List<String> UnitIDList = new ArrayList<>();
            for (BizObject obj2 : objs) {
                Map<String, Object> dicValueTable = new HashMap<>();
                if (obj2.getValueTable() != null) {
                    for (String pName : VisiblePropertyNames) {
                        if (obj2.getValueTable().containsKey(pName)) {
                            if (getSchema().GetProperty(pName).getLogicType() == DataLogicType.SingleParticipant || pName.equals(H3Property.CREATEDBY) || pName.equals("CreatedByParentId")) {
                                UnitIDList.add(obj2.getValueTable().get(pName) + "");
                            } else if (getSchema().GetProperty(pName).getLogicType() == DataLogicType.MultiParticipant && (participants = (String[]) obj2.getValueTable().get(pName)) != null && participants.length > 0) {
                                for (String participant : participants) {
                                    UnitIDList.add(participant);
                                }
                            }
                        }
                    }
                    List<Unit> Units = getEngine().getOrganization().GetUnits(UnitIDList);
                    Map<String, String> UnitDictionary = new HashMap<>();
                    for (Unit u : Units) {
                        if (!UnitDictionary.containsKey(u.getObjectID())) {
                            UnitDictionary.put(u.getObjectID(), u.getName());
                        }
                    }
                    for (String pName2 : VisiblePropertyNames) {
                        if (obj2.getValueTable().containsKey(pName2)) {
                            if (getSchema().GetProperty(pName2).getLogicType() == DataLogicType.SingleParticipant || pName2.equals(H3Property.CREATEDBY) || pName2.equals("CreatedByParentId")) {
                                dicValueTable.put(pName2, UnitDictionary.get(new StringBuilder().append(obj2.getValueTable().get(pName2)).append("").toString()) == null ? obj2.getValueTable().get(pName2) : UnitDictionary.get(obj2.getValueTable().get(pName2) + ""));
                            } else if (getSchema().GetProperty(pName2).getLogicType() == DataLogicType.MultiParticipant) {
                                String[] participants2 = (String[]) obj2.getValueTable().get(pName2);
                                if (participants2 == null || participants2.length <= 0) {
                                    dicValueTable.put(pName2, obj2.getValueTable().get(pName2));
                                } else {
                                    String multiParticipantString = "";
                                    for (String participant2 : participants2) {
                                        if (UnitDictionary.containsKey(participant2)) {
                                            multiParticipantString = multiParticipantString + UnitDictionary.get(participant2) + ";";
                                        } else {
                                            multiParticipantString = multiParticipantString + participant2 + ";";
                                        }
                                    }
                                    dicValueTable.put(pName2, multiParticipantString);
                                }
                            } else if (getSchema().GetProperty(pName2).getLogicType() == DataLogicType.TimeSpan) {
                                if (null != obj2.getValueTable().get(pName2)) {
                                    dicValueTable.put(pName2, ((TimeSpan) obj2.getValueTable().get(pName2)).toString());
                                }
                            } else if (getSchema().GetProperty(pName2).getLogicType() == DataLogicType.DateTime) {
                                if (null != obj2.getValueTable().get(pName2)) {
                                    dicValueTable.put(pName2, "/Date(" + Long.valueOf(DateTimeUtil.getStringToDate(obj2.getValueTable().get(pName2).toString()).getTime()) + ")/");
                                }
                            } else if (getSchema().GetProperty(pName2).getLogicType() == DataLogicType.Comment) {
                                dicValueTable.put(pName2, "");
                            } else {
                                dicValueTable.put(pName2, obj2.getValueTable().get(pName2));
                            }
                        }
                    }
                }
                dataList.add(dicValueTable);
            }
        }
        return dataList;
    }

    @RequestMapping(value = {"/GetBizQueryViewData"}, method = {RequestMethod.POST})
    @ResponseBody
    public Object GetBizQueryViewData(String schemaCode, String queryCode, String filterStr, PagerInfo pageInfo) throws Exception {
        if (StringUtils.isEmpty(queryCode) || Objects.equals(queryCode, "null")) {
            return ActionResult.fail("RunBizQuery.QueryCodeEmpty");
        }
        ActionResult actionResult = new ActionResult(false);
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> actionFilter = new HashMap<>();
        actionFilter.put("ContentEncoding", null);
        actionFilter.put("ContentType", null);
        actionFilter.put("Data", GetRunBizQueryData(schemaCode, queryCode));
        actionFilter.put("JsonRequestBehavior", 0);
        actionFilter.put("MaxJsonLength", null);
        actionFilter.put("RecursionLimit", null);
        param.put("ActionFilter", actionFilter);
        param.put("DisplayFormats", GetDisplayFormats());
        actionResult.setSuccess(true);
        actionResult.setExtend(param);
        Map<String, Object> result = new HashMap<>();
        result.put("Success", Boolean.valueOf(actionResult.getSuccess()));
        result.put("Extend", actionResult.getExtend());
        result.put("ExceptionCode", Integer.valueOf(actionResult.getExceptionCode().getValue()));
        result.put("Message", actionResult.getMessage());
        String currentUserId = getUserValidator().getUserID();
        new ArrayList<>().add(currentUserId);
        List<BizObjectAcl> boaList = getEngine().getBizObjectManager().GetBizObjectAcls(schemaCode, "");
        List<UnitType> unitTypeList = new ArrayList<>();
        unitTypeList.add(UnitType.User);
        unitTypeList.add(UnitType.OrganizationUnit);
        unitTypeList.add(UnitType.Group);
        boolean createBizObject = false;
        boolean administrator = false;
        if (getUserValidator().getUser().getIsAdministrator()) {
            createBizObject = true;
            administrator = true;
        } else {
            List<UnitType> unitTypes = new ArrayList<>();
            unitTypes.add(UnitType.OrganizationUnit);
            unitTypes.add(UnitType.User);
            unitTypes.add(UnitType.Group);
            for (BizObjectAcl boa : boaList) {
                String userId = boa.getUserID();
                if (userId.equals(currentUserId)) {
                    if (!createBizObject && boa.getCreateBizObject()) {
                        createBizObject = true;
                    }
                    if (!administrator && boa.getAdministrator()) {
                        administrator = true;
                    }
                } else {
                    for (Unit tempUnit : getEngine().getOrganization().GetChildUnits(userId, unitTypes, true, State.Active)) {
                        if (currentUserId.equals(tempUnit.getObjectID())) {
                            if (!createBizObject && boa.getCreateBizObject()) {
                                createBizObject = true;
                            }
                            if (!administrator && boa.getAdministrator()) {
                                administrator = true;
                            }
                        }
                    }
                }
            }
        }
        result.put("btnAddFlag", Boolean.valueOf(createBizObject));
        result.put("btnAdministratorFlag", Boolean.valueOf(administrator));
        return result;
    }
}
